import APIConfig from "../config/api";
import { wxToPromise } from './wx';
import exceptionMessage from '../config/exception-message';



let ajaxTimes = 0;
class Http {
      
    static async request( {url, data, method = "GET"} ) {
        ajaxTimes++;
        // console.log(ajaxTimes);
        wx.showLoading({
            title: "加载中",
            mask: true
        });
        let res = await wxToPromise("request", {
            url: APIConfig.baseUrl + url,
            method,
            data,
            complete:()=>{
                ajaxTimes--;
                // console.log(ajaxTimes);
                if(ajaxTimes === 0){
                    wx.hideLoading();
                }            
            }
        })


        if(res.statusCode < 400) {
            return res.data.data
        }

        if(res.statusCode === 401) {
            return
        }

        Http._showError(res.data.error_code, res.data.message);

    }


    static _showError(errorCode, message) {
        let title;
        const errorMessage = exceptionMessage[errorCode];
        title = errorMessage || message || "未知异常";
        title = typeof title === "object" ? Object.values(title).join() : title;
        wx.showToast({
            title,
            icon: 'none',
            duration: 3000
        })
    }
}


export default Http